// pages/pay/FacePay.js
// pages/pay/Pay.js
let Zan = require('../../dist/index.js');
let WxNotificationCenter = require('../../utils/WxNotificationCenter.js');
let network = null;
let utils = null;
let api = null;
const app = getApp();

Page(Object.assign({}, Zan.TopTips, Zan.Switch, {

  /**
   * 页面的初始数据
   */
  data: {
    totalPrice: 0,
    showDialog: false,
    store: null,
    couponPrice: 0, // 可优惠金额
    couponAmount: 0, // 优惠券面值
    couponId: 0, // 优惠券Id
    items: ['代金券', '会员折扣'],
    couponType: 0, // 优惠方式 
    member: null,
    selectCouponed: true,
    coupon: null,
    total: '',    
    notmoney: 0,
    allPrice: 0, // 总价
    discountPrice: 0, // 实付金额
    zhekou: 0,
    orderId: null,
    orderNO: null,
    orderDesc: null,
    useCoupon: false, // 是否使用优惠券
    mode1: 0,
    mode2: 1,
    radiochecked: 0,
    formId: '',
    multiIndex: [0, 0],
    StartingPrice: 0,
    coupon: [],
    notmoneytxt:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    network = new app.NetWorkUtils();
    utils = new app.Utils();
    api = new app.Api();

    let store = app.globalData.store;
    this.setData({
      store: store
    })
    console.log(this.data.store);
    console.log(app.globalData.userInfo);
    //判断会员卡到期
    if (app.globalData.userInfo.typeId) {
      if (app.globalData.userInfo.memberendtime) {
        var NowTime = new Date().getTime();
        var total_micro = app.globalData.userInfo.memberendtime * 1000 - NowTime;
        console.log("endTime" + app.globalData.userInfo.memberendtime * 1000);
        console.log("NowTime" + NowTime);
        console.log("total_micro" + total_micro);
        if (total_micro <= 0) {
          this.setData({
            items: ['代金券'],
          })
        } else {
          network._post_json(this, api.getUserMemberType, { typeId: app.globalData.userInfo.typeId }, memberTypeSuccess);
        }
      } else {
        network._post_json(this, api.getUserMemberType, { typeId: app.globalData.userInfo.typeId }, memberTypeSuccess);
      }
    } else {
      this.setData({
        items: ['代金券'],
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // },

  bindMultiPickerChange: function (e) {
    this.setData({
      multiIndex: e.detail.value,
      date: new Date().getTime() + e.detail.value[0] * 24 * 60 * 60 * 1000,
      dateLink: e.detail.value[1],
      dateStr: this.data.day[0][e.detail.value[0]] + this.data.day[1][e.detail.value[1]]
    })
  },

  /**
   * 弹出框开关
   */
  toggleDialog() {
    this.setData({
      showDialog: !this.data.showDialog
    })
  },
  total:function(e){
    this.setData({
      total: e.detail.value
    })
    let totalPrice = e.detail.value
    this.setData({
      couponPrice: 0,
      totalPrice: totalPrice,
      coupon: [],
      notmoneytxt: ''
    })

  },
  blurtotal:function(e){
    this.setData({
      total: Math.floor(e.detail.value * 100) / 100
    })
    let totalPrice = e.detail.value
    this.setData({
      totalPrice: totalPrice,
      coupon: []
    })
    console.log(this.data.total);
    if (this.data.total && this.data.couponType == 0 && this.data.totalPrice > 0) {
      network._post_json(this, api.getCanUseCoupons, { price: this.data.totalPrice * 100, storeId: app.globalData.store.id }, Couponsuccess);
    }
  },
  notmoney: function (e) {
    this.setData({
      couponPrice: 0,
    })
    if (parseInt(e.detail.value) > parseInt(this.data.total)){
      this.showZanTopTips(2, '不参与优惠金额不能大于消费金额');
      this.setData({
        notmoneytxt:''
      })
    }else{
      this.setData({
        notmoney: e.detail.value
      })
      let totalPrice = this.data.total - e.detail.value
      this.setData({
        totalPrice: totalPrice,
        coupon: []
      })
      if (this.data.total && this.data.couponType == 0 && this.data.totalPrice > 0) {
        network._post_json(this, api.getCanUseCoupons, { price: this.data.totalPrice * 100, storeId: app.globalData.store.id }, Couponsuccess);
      }else{
        console.log("=========暂无可用优惠券==========");
        var timer = setTimeout(this.Refresh,200);
        
      }
    }
  },
  notmoneytotal:function(e){
    this.setData({
      notmoneytxt: Math.floor(e.detail.value * 100) / 100,
      notmoney: Math.floor(e.detail.value * 100) / 100
    })
    let totalPrice = this.data.total - Math.floor(e.detail.value * 100) / 100
    this.setData({
      totalPrice: totalPrice,
    })
  },
  Refresh(){
    this.setData({
      coupon: []
    })
  },
  /**
   * 选择优惠方式
   * 0代金券 1会员折扣
   */
  radioButtonTap: function (e) {
    console.log(e);
    this.setData({
      couponType: e.detail
    })
    if (this.data.total && this.data.notmoney){
      if (e.detail == 1) {
        if (this.data.member && this.data.member.rule.isMemBerShop == 1) {
          // 折扣
          this.setData({
            couponPrice: this.data.totalPrice - parseInt(this.data.totalPrice * this.data.member.rule.memberDiscounts / 10)
          })
        }
      } else {
        this.setData({
          couponPrice: this.data.couponAmount
        })
      }
      console.log("========couponPrice=======" + this.data.couponPrice);
    }else{
      this.showZanTopTips(2, '请输入金额');
    }
  },

  /**
   * 选择优惠券
   */
  chooseCoupon: function (e) {
    this.setData({
      coupon: []
    })
    if (this.data.total && this.data.couponType == 0){
      if (this.data.totalPrice > 0){
        network._post_json(this, api.getCanUseCoupons, { price: this.data.totalPrice * 100, storeId: app.globalData.store.id }, Couponsuccess);
        this.setData({
          showDialog: !this.data.showDialog
        })
      }else{
        this.showZanTopTips(2, '暂无可用优惠券');
      }
    }else{
      this.showZanTopTips(2, '请输入消费金额');
    }
    
  },

  /**
   * 获取选择的优惠券
   */
  // 领取优惠券
  userCoupon: function (e) {
    var coupon = e.currentTarget.dataset.item;
    this.setData({
      couponAmount: coupon.value2,
      couponPrice: coupon.value2,
      couponId: coupon.id
    })
    console.log(this.data.couponId);
    this.setData({
      showDialog: !this.data.showDialog
    })
  },
  //确定
  formSubmit: function (e) {
    let data = {};
    if (e.detail.value.total){
      
      data.price = e.detail.value.total;
      if (e.detail.value.notmoney){
        data.solidFee = e.detail.value.notmoney;
      }else{
        data.solidFee = 0;
      }
      
      data.storeId = app.globalData.store.id;
      if (this.data.couponType == 0) {
        data.couponId = this.data.couponId;
        data.memberId = ''
      } else {
        if (this.data.member) {
          data.memberId = this.data.member.membertype_id;
          data.couponId = ''
        }
      }
      network._post_json(this, api.faceOrder, data, faceSuccess);
    }else{
      this.showZanTopTips(2, '请输入金额');
    }
    
  }

}))

/**
 * 会员优惠
 */
var memberTypeSuccess = function (that, res) {
  if (res.data.data) {
    if (res.data.data.rule.isMemBerShop == 1){
      that.setData({
        items: ['代金券', '会员折扣']
      })
    } else if (res.data.data.rule.isMemBerShop == 0){
      that.setData({
        items: ['代金券', '会员价']
      })
    }
    that.setData({
      member: res.data.data,
    })
  }
}
// 当前商品可使用优惠券
var Couponsuccess = function (that, res) {
  that.setData({
    coupon: []
  })
  if (res.data.data) {
    var coupon = res.data.data;
    for (var i = 0; i < coupon.length; i++) {
      coupon[i].startTime = utils.formatDate02(new Date(coupon[i].startTime * 1000))
      coupon[i].endTime = utils.formatDate02(new Date(coupon[i].endTime * 1000))
    }
    that.setData({
      coupon: that.data.coupon.concat(coupon),
    })
    console.log(that.data.coupon);
  }
}

var faceSuccess = function(that,res){
  let order = {};
  order.orderId = res.data.data.id;
  // order.orderNO = res.data.data.orderNo;
  order.totalPrice = res.data.data.price;
  order.couponPrice = res.data.data.saleMoney;
  console.log(order);
  wx.navigateTo({
    url: '/pages/pay/ChoosePay2?order=' + JSON.stringify(order) + '&store=' + encodeURIComponent(JSON.stringify(that.data.store))
  })
}